use std::net::{Shutdown,TcpListener,TcpStream};
use std::thread;
use std::io::prelude::*;

fn handle_client(mut stream: TcpStream) {
    // ...
    let mut buffer = [0;10];

    stream.read(&mut buffer);

    stream.write(&[5,0]);

    stream.read(&mut buffer);

    let ip_port = format!("{:?}.{:?}.{:?}.{:?}:{:?}", buffer[4],buffer[5],buffer[6],buffer[7],256* (buffer[8] as i32) + (buffer[9] as i32));

    println!("连接服务器:{:?}", &ip_port);

    // &*ip_port
  	match TcpStream::connect(&*ip_port){
  			Ok(mut remote)=>{
  				//连接服务器成功后...
  				stream.write(&[5,0,0,1,buffer[4],buffer[5],buffer[6],buffer[7],buffer[8],buffer[9]]);

  				
  				
  				let mut stream_reader = stream.try_clone().unwrap();
  				let mut remote_writer = remote.try_clone().unwrap();
  				thread::spawn(move|| {
	                  let mut bbb = [0;1024];
	                  //stream_reader.set_nonblocking(true);
	                  loop{
	                  	   match stream_reader.read(&mut bbb) {
		                  	   	Ok(0) => {break;},
		                  	   	Ok(n) => { remote_writer.write(&bbb[0..n]);remote_writer.flush();},
		                  	   	Err(_) => {break;},
	                  	   }
	                  }
	            });

  				
  				
              let mut bbb = [0;1024*2];
              loop{

              	   match remote.read(&mut bbb) {
                  	   	Ok(0) => {break;},
                  	   	Ok(n) => { stream.write(&bbb[0..n]);stream.flush();},
                  	   	Err(_) => {break;},
              	   }
              }

              stream.shutdown(Shutdown::Both);
              remote.shutdown(Shutdown::Both);
	     
  				
  			 },
  			Err(_)=>{println!("连接失败...."); stream.write(&[5,0,0,1,0,0,0,0,0,0]);}
  	}


  	//stream.shutdown(Shutdown::Both);

}

fn main() {
	
	let listener = TcpListener::bind("0.0.0.0:8088").unwrap();
	//listener.set_nonblocking(true);


    for stream in listener.incoming() {
	    match stream {
	        Ok(stream) => {
	            thread::spawn(move|| {
	                // connection succeeded
	                handle_client(stream)
	            });
	        }
	        Err(e) => { println!("{:?}", e); }
	    }
	}

	// close the socket server
	drop(listener);
}